const map = new Map<string, HTMLLinkElement>();
export function unload(src: string) {
  const item = map.get(src);
  if (!item) {
    return;
  }
  item.remove();
  map.delete(src);
}

type ISrc = string | undefined;

export function preload(...srcList: Array<ISrc[] | ISrc>) {
  if (!srcList.length) {
    return;
  }
  const list = srcList.flat().filter((item): item is string => !!item);
  list.map(src => {
    if (map.has(src)) {
      return;
    }
    const linkEle = document.createElement('link');
    linkEle.href = src;
    linkEle.rel = 'prefetch';
    map.set(src, linkEle);
    const _unload = () => unload(src);
    linkEle.addEventListener('load', _unload, { once: true });
    linkEle.addEventListener('error', _unload, { once: true });
    document.head.appendChild(linkEle);
  });
}